package com.liangxy.news.ui.main.settings;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.liangxy.news.R;
import com.liangxy.news.api.ApiClient;
import com.liangxy.news.repository.NewsRepository;
import com.liangxy.news.util.SharedPreferencesManager;
import com.liangxy.news.database.AppDatabase;

/**
 * 设置界面Fragment
 */
public class SettingsFragment extends Fragment {
    
    private static final String TAG = "SettingsFragment";
    
    private NewsRepository newsRepository;
    private SharedPreferencesManager preferencesManager;
    private Switch switchUseMockData;
    private EditText etApiKey;
    private Button btnSaveApiKey;
    
    public static SettingsFragment newInstance() {
        return new SettingsFragment();
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        newsRepository = NewsRepository.getInstance(requireContext());
        preferencesManager = new SharedPreferencesManager(requireContext());
        
        // 初始化ApiClient
        ApiClient.init(requireContext());
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_settings, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化开关和输入框
        switchUseMockData = view.findViewById(R.id.switch_use_mock_data);
        etApiKey = view.findViewById(R.id.etApiKey);
        btnSaveApiKey = view.findViewById(R.id.btnSaveApiKey);
        
        // 设置开关状态
        switchUseMockData.setChecked(newsRepository.isUsingMockData());
        
        // 设置API密钥
        etApiKey.setText(ApiClient.getApiKey());
        
        // 设置开关监听器
        switchUseMockData.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                newsRepository.setUseMockData(isChecked);
                
                // 强制刷新所有分类的新闻数据
                refreshAllNewsCategories();
                
                Toast.makeText(requireContext(), 
                        isChecked ? "已切换到模拟数据模式，请返回首页查看" : "已切换到API数据模式，请返回首页查看", 
                        Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置保存API密钥按钮点击事件
        btnSaveApiKey.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveApiKey();
            }
        });
    }
    
    /**
     * 保存API密钥
     */
    private void saveApiKey() {
        String apiKey = etApiKey.getText().toString().trim();
        if (TextUtils.isEmpty(apiKey)) {
            Toast.makeText(requireContext(), "API密钥不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 保存API密钥
        ApiClient.saveApiKey(requireContext(), apiKey);
        
        // 清理数据库并刷新数据
        if (!newsRepository.isUsingMockData()) {
            clearDatabase();
            refreshAllNewsCategories();
        }
        
        Toast.makeText(requireContext(), "API密钥保存成功，将使用新密钥请求数据", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "API密钥已更新: " + apiKey);
    }
    
    /**
     * 强制刷新所有分类的新闻数据
     */
    private void refreshAllNewsCategories() {
        // 清理数据库中的旧数据
        clearDatabase();
        
        // 刷新常用分类的新闻
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_TOP, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_GUONEI, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_GUOJI, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_YULE, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_TIYU, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_JUNSHI, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_KEJI, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_CAIJING, 1, 20);
        newsRepository.refreshNewsByCategory(NewsRepository.TYPE_SHISHANG, 1, 20);
    }
    
    /**
     * 清理数据库中的旧数据
     */
    private void clearDatabase() {
        new Thread(() -> {
            try {
                // 获取数据库实例
                AppDatabase db = AppDatabase.getInstance(requireContext());
                // 清理新闻表
                db.newsDao().deleteAll();
                // 清理新闻详情表
                db.newsDetailDao().deleteAll();
                
                Log.d(TAG, "数据库清理完成");
            } catch (Exception e) {
                Log.e(TAG, "清理数据库出错: " + e.getMessage(), e);
            }
        }).start();
    }
} 